package com.rrd.dw.mr.gzip.kafka;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ucredit.babel.common.model.BaseModel;
import com.ucredit.babel.common.model.RecordType;
import com.ucredit.babel.common.model.third.smartdata.SmartDataData;
import com.ucredit.babel.common.model.third.smartdata.SmartDataRecord;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;

import java.io.IOException;

/**
 * 智数消费能力
 *
 * @author renzhanzheng
 */

public class SmartDataParse extends ParseBase {
    private Text val = new Text();
    private Text key = new Text();

    /**
     * 智数消费能力
     *
     * @param model
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public boolean parseJob(Context context, BaseModel<?> model, String successful) throws IOException, InterruptedException {
        SmartDataRecord obj = (SmartDataRecord)model;
        SmartDataData smartDataData = obj.getSmartDataData();
        JSONObject info = smartDataData.getData() == null ? new JSONObject() : JSON.parseObject(smartDataData.getData());
        JSONObject head = info.getJSONObject("head") == null ? new JSONObject() : info.getJSONObject("head");
        JSONObject body = info.getJSONObject("body") == null ? new JSONObject() : info.getJSONObject("body");

        StringBuilder sb = getBaseInfo(obj, successful);
        //平台状态码
        sb.append(head.getString("code") == null ? "" : head.getString("code")).append(CRT001);
        //请求ID
        sb.append(head.getString("serialID") == null ? "" : head.getString("serialID")).append(CRT001);
        //平台状态信息
        sb.append(head.getString("codeInfo") == null ? "" : head.getString("codeInfo")).append(CRT001);
        //近期消费水平等级
        sb.append(body.getString("result") == null ? "" : body.getString("result")).append(CRT001);
        //订单号
        sb.append(body.getString("orderID") == null ? "" : body.getString("orderID")).append(CRT001);
        //hashValue
        sb.append(info.getString("hashValue") == null ? "" : info.getString("hashValue")).append(CRT001);

        key.set(getKey());
        val.set(sb.toString().replace("\n", " ").replace("\r", " "));
        context.write(key, val);
        return true;
    }

    @Override
    public String getTableName() {
        return "kafka_babel_zhishu_consumption_inc";
    }

    @Override
    public String getType() {
        return RecordType.SMART_DATA_RECORD.toString();
    }

    @Override
    public String getComment() {
        return "智数消费能力";
    }
}
